package 多线程和队列.锁;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * java8 之前 sychronized  wait notify  notifyAll
 * java8 以后 lock  await  signal
 * java8 中实现对锁的控制
 *
 * @author 孔令富  2021/12/21
 */
class ShareData{
    private int number = 0 ;

    private final Lock lock = new ReentrantLock();
    private final Condition  condition = lock.newCondition();

    public void increment() throws InterruptedException {
        lock.lock();
        try{
            while(number !=0 ){
              condition.await();
            }
            ++number ;
            System.out.println(Thread.currentThread().getName()+"\t"+number);
            condition.signalAll();
        } finally{
            lock.unlock();
        }

    }

    public void decrement() throws InterruptedException {
        lock.lock();

        try{
            while(number != 1){
                condition.await();
            }
            --number;
            System.out.println(Thread.currentThread().getName()+"\t"+number);
            condition.signalAll();
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

}

public class ConditionDemo {

    public static void main(String[] args) {
          ShareData shareData = new ShareData();
            for (int i = 0; i < 10; i++) {
               new Thread(()->{
                   try {
                       shareData.increment();
                   } catch (InterruptedException exception) {
                       exception.printStackTrace();
                   }
               }).start();
            }

        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                try {
                    shareData.decrement();
                } catch (InterruptedException exception) {
                    exception.printStackTrace();
                }
            }).start();
        }
    }


}
